package net.lab1024.sa.admin.module.crawler.service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import net.lab1024.sa.admin.module.crawler.dao.ShopDao;
import net.lab1024.sa.admin.module.crawler.domain.entity.ShopEntity;
import net.lab1024.sa.admin.module.crawler.domain.form.*;
import net.lab1024.sa.admin.module.crawler.domain.vo.ShopVO;
import net.lab1024.sa.admin.module.crawler.manager.ShopManager;
import net.lab1024.sa.base.common.domain.RequestUser;
import net.lab1024.sa.base.common.util.*;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.domain.PageResult;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.lab1024.sa.base.constant.TpTypeConst;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;

/**
 * 门店 Service
 *
 * @Author -
 * @Date 2025-03-21 08:31:36
 * @Copyright -
 */

@Service
public class ShopService {

    @Resource
    private ShopDao shopDao;

    @Autowired
    TpUtilService tpUtilService;


    public ResponseDTO<String> getMtRequestUrl(RequestUrlParmForm form) {
        return ResponseDTO.ok(tpUtilService.getMtRequestUrl(form.getCookiestr(), form.getPageNum()));
    }

    /**
     * 分页查询
     *
     * @param queryForm
     * @return
     */
    public PageResult<ShopVO> queryPage(ShopQueryForm queryForm) {
        Page<?> page = SmartPageUtil.convert2PageQuery(queryForm);
        List<ShopVO> list = shopDao.queryPage(page, queryForm);
        PageResult<ShopVO> pageResult = SmartPageUtil.convert2PageResult(page, list);
        return pageResult;
    }

    public List<ShopVO> selectList(ShopselectListQueryForm queryForm) {
        Long requestUserId = SmartRequestUtil.getRequestUserId();
        assert requestUserId != null;
        List<ShopEntity> shopEntities = shopDao.selectList(new QueryWrapper<ShopEntity>()
                .select("id", "shop_id", "CONCAT(shop_name,'(',shop_id,')') as shop_name")
                .eq("tp", TpTypeConst.JDCY)
                .eq("auth_status", 1)
                .eq(!requestUserId.equals(1L), "user_id", requestUserId)
                .and(SmartStringUtil.isNotBlank(queryForm.getShopKey()),qw -> qw.like("shop_id", queryForm.getShopKey())
                        .or().like("shop_name", queryForm.getShopKey()))
                .orderByDesc("auth_time")
                .last("limit 10")
        );
        return SmartBeanUtil.copyList(shopEntities, ShopVO.class);
    }

    /**
     * 添加
     */
    public ResponseDTO<String> add(ShopAddForm addForm) {

        RequestUser requestUser = SmartRequestUtil.getRequestUser();
        String shopId = addForm.getShopId();
        List<ShopAddForm> shops = new ArrayList<>();
        //连锁门店
        if ("-1".equals(shopId)) {
            shops = tpUtilService.authShop(addForm);
        } else {
            shops.add(addForm);
        }
        if (!CollectionUtils.isEmpty(shops)) {
            shops.forEach(shop -> {
                ShopEntity shopEntity = SmartBeanUtil.copy(shop, ShopEntity.class);
                ShopEntity entity = shopDao.selectOne(new QueryWrapper<ShopEntity>()
                        .eq("shop_id", addForm.getShopId())
                        .eq("user_id", requestUser.getUserId())
                        .last("limit 1")
                );
                shopEntity.setAuthIp(requestUser.getIp());
                shopEntity.setAuthTime(LocalDateTime.now());
                shopEntity.setUserId(requestUser.getUserId());
                if (entity != null) {
                    shopEntity.setId(entity.getId());
                    shopDao.updateById(shopEntity);
                } else {
                    shopDao.insert(shopEntity);
                }
            });
        } else {
            return ResponseDTO.userErrorParam("未获取门店！");
        }
        return ResponseDTO.ok();
    }

    /**
     * 更新
     *
     * @param updateForm
     * @return
     */
    public ResponseDTO<String> update(ShopUpdateForm updateForm) {
        ShopEntity shopEntity = SmartBeanUtil.copy(updateForm, ShopEntity.class);
        shopDao.updateById(shopEntity);
        return ResponseDTO.ok();
    }

    /**
     * 批量删除
     *
     * @param idList
     * @return
     */
    public ResponseDTO<String> batchDelete(List<Long> idList) {
        if (CollectionUtils.isEmpty(idList)) {
            return ResponseDTO.ok();
        }

        shopDao.batchUpdateDeleted(idList, true);
        return ResponseDTO.ok();
    }

    /**
     * 单个删除
     */
    public ResponseDTO<String> delete(Long id) {
        if (null == id) {
            return ResponseDTO.ok();
        }

        shopDao.updateDeleted(id, true);
        return ResponseDTO.ok();
    }
}
